/*
 * Created by: Peter Weissbrod
 * Created: Saturday, November 03, 2007
 */
using System.Collections.Generic;
using Castle.ActiveRecord;
using NHibernate.Expression;
using Utils;

namespace EntityLayer.Entities
{
    /// <summary>
    /// The data definition for a user
    /// </summary>
    [ActiveRecord("Users")]
    public class User : ActiveRecordBase<User>
    {
        #region members
        private string passwordHash = Nulls.String;
        private IList<SalesItem> salesItems = new List<SalesItem>();
        private int userID = Nulls.ID;
        private string userName = Nulls.String;
        private Enumerations.UserPrivileges userPrivilege = Enumerations.UserPrivileges.Null;
        #endregion

        #region properties
        [PrimaryKey(PrimaryKeyType.Identity, "UserID")]
        public int UserID
        {
            get { return userID; }
            set { userID = value; }
        }
        [Property(NotNull = true, Length = 255)]
        [ValidateIsUnique("This user name is already in use")]
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
        [Property(NotNull = true, Length = 1000)]
        public string PasswordHash
        {
            get { return passwordHash; }
            set { passwordHash = value; }
        }
        [Property(NotNull = true)]
        public Enumerations.UserPrivileges UserPrivilege
        {
            get { return userPrivilege; }
            set { userPrivilege = value; }
        }
        [HasMany(Table = "SalesItems", ColumnKey = "UserID", Lazy = true, Inverse = true,
            Cascade = ManyRelationCascadeEnum.AllDeleteOrphan)]
        public IList<SalesItem> SalesItems
        {
            get { return salesItems; }
            set { salesItems = value; }
        }
        #endregion

        #region methods
        public User()
        {
        }
        public User(string userName, string passwordHash)
        {
            this.UserPrivilege = Enumerations.UserPrivileges.StandardUser;
            this.userName = userName;
            this.passwordHash = passwordHash;
        }
        public static User GetUserByPassword(string userName, string clearTextPassword)
        {
            string hashedPassword = Crypto.Hash(clearTextPassword);
            return FindOne(Expression.And(
                               Expression.Eq("UserName", userName),
                               Expression.Eq("PasswordHash", hashedPassword))
                );
        }
        #endregion
    }
}